﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class ViewMeetingsForm : Form
    {
        public ViewMeetingsForm(bool report)
        {
            InitializeComponent();
            this.report = report;
            this.ShowInTaskbar = false;
        }

        int regID, avpID;
        tb_meeting meeting;
        bool visitors, report;

        private void butEdit_Click(object sender, EventArgs e)
        {
            if (dgvMeetings.RowCount > 0 && avpID > 0)
            {
                rresFalse.Visible = rresTrue.Visible = editCBType.Visible = editDtpDate.Visible = editlabel3.Visible = editlabel4.Visible =
                    editlabel5.Visible = editlabel6.Visible = editlabel8.Visible = editTBNote.Visible = editTBQuestions.Visible =
                    editTBVisitors.Visible = editButtonAccept.Visible = dgvMeetings.Visible;


                dgvMeetings.Visible = !editTBVisitors.Visible;

                meeting = DBClass.Meetings
                    .Where(wh => wh.ID == (int)dgvMeetings["ID", dgvMeetings.CurrentRow.Index].Value && wh.AVPID == avpID)
                    .FirstOrDefault();

                if (meeting != null)
                {
                    rresTrue.Checked = (bool)meeting.Results.Value;
                    editCBType.SelectedValue = (int)meeting.TypeID;
                    editDtpDate.Value = meeting.Date;
                    editTBNote.Text = meeting.Note;
                    editTBQuestions.Text = meeting.Questions;
                    editTBVisitors.Text = meeting.Visitors;
                }
            }
        }


        private void ViewMeetingsForm_Load(object sender, EventArgs e)
        {


            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = DBClass.Regions.Select(se => new { Name = se.Name, ID = se.ID }).OrderBy(o => o.Name).ToList();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";
            cbRegion.SelectedIndex = -1;
            cbRegion.SelectedIndexChanged += new System.EventHandler(this.cbRegion_SelectedIndexChanged);


            cbMeetingtype.SelectedIndexChanged -= cbMeetingtype_SelectedIndexChanged;

            cbMeetingtype.DataSource = DBClass.MeetingTypes.Select(se => new { NameRus = se.NameRus, NameUzb = se.NameUzb, ID = se.ID }).ToList();
            if (InformationClass.Lang)
                cbMeetingtype.DisplayMember = "NameRus";
            else
                cbMeetingtype.DisplayMember = "NameUzb";
            cbMeetingtype.ValueMember = "ID";

            cbMeetingtype.SelectedIndex = -1;

            cbMeetingtype.SelectedIndexChanged += new EventHandler(this.cbMeetingtype_SelectedIndexChanged);

            buttonShow.Enabled = cbAVP.Enabled = false;

            cbYear.Items.Add(string.Empty);
            for (int i = 1991; i <= DateTime.Now.Year; i++)
            {
                cbYear.Items.Add(i);
            }

            if (report)
            {
                butEdit.Visible = butDelete.Visible = false;
                
                //buttonReport.Visible = true;
            }
            else
            {
                butEdit.Visible = butDelete.Visible = true;
                buttonExcel.Visible = false;
                if (InformationClass.Lang)
                    editCBType.DataSource = DBClass.MeetingTypes.Select(se => new { Name = se.NameRus, ID = se.ID }).OrderBy(o => o.Name).ToList();
                else
                    editCBType.DataSource = DBClass.MeetingTypes.Select(se => new { Name = se.NameUzb, ID = se.ID }).OrderBy(o => o.Name).ToList();
                editCBType.DisplayMember = "Name";
                editCBType.ValueMember = "ID";
                editCBType.SelectedIndex = -1;
                editCBType.Text = string.Empty;

            }

            if (!InformationClass.isAdmin)
            {
                regID = InformationClass.regionID;
                cbRegion.SelectedValue = regID;
                cbRegion.Enabled = false;
            }

        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                buttonShow.Enabled = cbAVP.Enabled = true;

                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;

                cbAVP.DataSource = DBClass.AVP.Where(wh => wh.RegionID == Convert.ToInt32(cbRegion.SelectedValue)).Select(se => new { Name = se.Name, ID = se.ID }).OrderBy(o => o.Name).ToList();
                cbAVP.DisplayMember = "Name";
                cbAVP.ValueMember = "ID";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;

                regID = Convert.ToInt32(cbRegion.SelectedValue);

                cbAVP.SelectedIndexChanged += new System.EventHandler(this.cbAVP_SelectedIndexChanged);
            }
            else
            {
                cbAVP.DataSource = null;
                cbAVP.Text = string.Empty;
            }

        }

        private void rbAllMeetings_CheckedChanged(object sender, EventArgs e)
        {
            cbMeetingtype.Enabled = rbMeetingType.Checked;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            ShowMeetings();
        }

        private void ShowMeetings()
        {
            int[] avp = DBClass.AVP
                        .Where(whr => whr.RegionID == regID)
                        .Select(se => se.ID)
                        .ToArray();
            var res = DBClass.Meetings
                .Where(wh => avp.Contains(wh.AVPID));

            if (cbAVP.SelectedIndex >= 0)
                res = res.Where(wh => wh.AVPID == avpID);

            if (rbMeetingType.Checked)
            {
                res = res.Where(wh => wh.TypeID == Convert.ToInt32(cbMeetingtype.SelectedValue));
            }

            if (chbDate.Checked)
            {
                if (cbYear.SelectedIndex >= 0)
                    res = res.Where(wh => wh.Date.Year == Convert.ToInt32(cbYear.Items[cbYear.SelectedIndex]));
                if (chbKV1.Checked)
                    res = res.Where(wh => wh.Date.Month <= 3);
                if (chbKV2.Checked)
                    res = res.Where(wh => wh.Date.Month >= 4 && wh.Date.Month <= 6);
                if (chbKV3.Checked)
                    res = res.Where(wh => wh.Date.Month >= 7 && wh.Date.Month <= 9);
                if (chbKV4.Checked)
                    res = res.Where(wh => wh.Date.Month >= 10);
            }
            if (chbResult.Checked)
            {
                res = res.Where(wh => wh.Results == rbResultTrue.Checked);
            }

            //res = res.Select(se => new
            //{
            //    ID = se.ID,
            //    MAVP = UtilClass.GetAVPName(se.AVPID),
            //    MType = UtilClass.getMeetingName(se.TypeID),
            //    MDate = se.Date.Date,
            //    MQuestions = se.Questions,
            //    MVisitors = se.Visitors,
            //    MResult = UtilClass.GetCategoryDisplayName((int)se.Results, "MeetingResult"),
            //    MNote = se.Note
            //});

            dgvMeetings.DataSource = res.Select(se => new
            {
                ID = se.ID,
                MAVP = UtilClass.GetAVPName(se.AVPID),
                MType = UtilClass.getMeetingName(se.TypeID),
                MDate = se.Date,
                MQuestions = se.Questions,
                MVisitors = se.Visitors,
                MResult = se.Results,
                MNote = se.Note
            }).ToList();

            if (InformationClass.Lang)
            {
                dgvMeetings.Columns["MAVP"].HeaderText = "АВП";
                dgvMeetings.Columns["MType"].HeaderText = "Тип собрания";
                dgvMeetings.Columns["MDate"].HeaderText = "Дата";
                dgvMeetings.Columns["MQuestions"].HeaderText = "Вопросы";
                dgvMeetings.Columns["MVisitors"].HeaderText = "Посетители";
                dgvMeetings.Columns["MResult"].HeaderText = "Результат";
                dgvMeetings.Columns["MNote"].HeaderText = "Примечание";
            }
            else
            {
                dgvMeetings.Columns["MAVP"].HeaderText = "СИУ";
                dgvMeetings.Columns["MType"].HeaderText = "Йиғилиш тури";
                dgvMeetings.Columns["MDate"].HeaderText = "Сана";
                dgvMeetings.Columns["MQuestions"].HeaderText = "Саволлар";
                dgvMeetings.Columns["MVisitors"].HeaderText = "Ташриф қилувчилар";
                dgvMeetings.Columns["MResult"].HeaderText = "Натижа";
                dgvMeetings.Columns["MNote"].HeaderText = "Изоҳ";
            }


            dgvMeetings.AutoResizeColumns();
            dgvMeetings.Columns["MVisitors"].Visible = visitors;
            dgvMeetings.Columns["ID"].Visible = false;
        }

        private void chbDate_CheckedChanged(object sender, EventArgs e)
        {
            groupBox3.Enabled = chbDate.Checked;
        }

        private void cbMeetingtype_SelectedIndexChanged(object sender, EventArgs e)
        {
            visitors = DBClass.MeetingTypes
                .Where(wh => wh.ID == Convert.ToInt32(cbMeetingtype.SelectedValue))
                .Select(se => se.Visitors)
                .SingleOrDefault();
        }

        private void editButtonAccept_Click(object sender, EventArgs e)
        {
            if (meeting != null)
            {
                meeting.Visitors = editTBVisitors.Text;
                meeting.TypeID = Convert.ToInt32(editCBType.SelectedValue);
                meeting.Results = rbResultTrue.Checked;
                meeting.Questions = editTBQuestions.Text;
                meeting.Note = editTBNote.Text;
                meeting.Date = editDtpDate.Value.Date;

                try
                {
                    DBClass.RESPContext.SubmitChanges();
                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                    rresFalse.Visible = rresTrue.Visible = editCBType.Visible = editDtpDate.Visible = editlabel3.Visible = editlabel4.Visible =
                        editlabel5.Visible = editlabel6.Visible = editlabel8.Visible = editTBNote.Visible = editTBQuestions.Visible =
                        editTBVisitors.Visible = editButtonAccept.Visible = dgvMeetings.Visible;

                    ShowMeetings();
                    dgvMeetings.Visible = !editTBVisitors.Visible;
                }
                catch
                {
                    MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                }
            }


        }

        private void butDelete_Click(object sender, EventArgs e)
        {
            if (dgvMeetings.RowCount > 0 && avpID > 0)
            {

                meeting = DBClass.Meetings
                    .Where(wh => wh.ID == (int)dgvMeetings["ID", dgvMeetings.CurrentRow.Index].Value && wh.AVPID == avpID)
                    .FirstOrDefault();

                DBClass.RESPContext.tb_meetings.DeleteOnSubmit(meeting);
                DBClass.RESPContext.SubmitChanges();
                ShowMeetings();
            }

        }

        private void chbResult_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void dgvMeetings_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvMeetings.Columns.Contains("MResult"))
            {
                if (e.ColumnIndex.Equals(dgvMeetings.Columns["MResult"].Index) && e.Value != null)
                {
                    string ResTrue = InformationClass.Lang ? "Положительный" : "Ижобий";
                    string ResFalse = InformationClass.Lang ? "Отрицательный" : "Салбий";

                    string newVal = (bool)e.Value ? ResTrue : ResFalse;
                    if (String.IsNullOrEmpty(newVal))
                        e.Value = "no data";
                    else
                        e.Value = newVal;
                }
            }
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvMeetings.RowCount > 0)
            {
                Sheets excelsheets;
                Worksheet excelworksheet;
                Microsoft.Office.Interop.Excel.Application excelapp;
                Workbook excelappworkbook;
                Workbooks excelappworkbooks;
                excelapp = new Microsoft.Office.Interop.Excel.Application();
                excelapp.SheetsInNewWorkbook = 1;

                if (InformationClass.Lang)
                    excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r3.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                else
                    excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r3uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                excelappworkbook = excelapp.Workbooks[1];
                excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
                excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

                excelworksheet.Cells.NumberFormat = "@";

                if (chbDate.Checked)
                {
                    excelworksheet.Cells[6, 2] = cbYear.Text;
                    if (chbKV1.Checked)
                        excelworksheet.Cells[6, 3] = chbKV1.Text +" "+cbYear.Text+" года";
                    if (chbKV2.Checked)
                        excelworksheet.Cells[6, 2] = chbKV2.Text + " " + cbYear.Text + " года";
                    if (chbKV3.Checked)
                        excelworksheet.Cells[6, 2] = chbKV3.Text + " " + cbYear.Text + " года";
                    if (chbKV4.Checked)
                        excelworksheet.Cells[6, 2] = chbKV4.Text + " " + cbYear.Text + " года";

                }
                excelworksheet.Cells[4, 3] = cbRegion.Text;
                //for (int i = 0; i < dgvReportView.Columns.Count; i++)
                //    excelworksheet.Cells[1, dgvReportView.Columns[i].DisplayIndex + 1] = dgvReportView.Columns[i].HeaderText.ToString();
                for (int i = 0; i < dgvMeetings.Rows.Count; i++)
                {
                    //for (int j = 0; j < dgvMeetings.Columns.Count; j++)
                    //{
                    //    if (dgvMeetings.Columns[j].Visible)
                    //        excelworksheet.Cells[i + 8, dgvMeetings.Columns[j].DisplayIndex + 3] = dgvMeetings[j, i].FormattedValue;
                    //}

                    // прописывать вручную
                    excelworksheet.Cells[i + 8, dgvMeetings.Columns["MAVP"].DisplayIndex + 2] = dgvMeetings["MAVP", i].FormattedValue;
                    excelworksheet.Cells[i + 8, dgvMeetings.Columns["MType"].DisplayIndex + 2] = dgvMeetings["MType", i].FormattedValue;
                    excelworksheet.Cells[i + 8, dgvMeetings.Columns["MDate"].DisplayIndex + 2] = dgvMeetings["MDate", i].FormattedValue;
                    excelworksheet.Cells[i + 8, dgvMeetings.Columns["MQuestions"].DisplayIndex + 2] = dgvMeetings["MQuestions", i].FormattedValue;
                    excelworksheet.Cells[i + 8, dgvMeetings.Columns["MResult"].DisplayIndex + 1] = dgvMeetings["MResult", i].FormattedValue;
                    excelworksheet.Cells[i + 8, dgvMeetings.Columns["MNote"].DisplayIndex + 1] = dgvMeetings["MNote", i].FormattedValue;


                    //
                    excelworksheet.Cells[i + 8, 2] = i + 1;
                }

                excelworksheet.Columns.AutoFit();

                excelworksheet.Select(1);
                excelapp.Visible = true;
            }
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
